<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8" />
    <title>知识库管理</title>
    <!-- 引入jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入Bootstrap -->
    <link
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <style>
      .container {
        padding: 20px;
      }
      .table-responsive {
        margin-top: 20px;
      }
      .action-buttons {
        white-space: nowrap;
      }
    </style>
  </head>
  <body th:fragment="content">
    <div class="container">
      <div class="d-flex justify-content-between align-items-center">
        <h2>知识库管理</h2>
        <button class="btn btn-primary" onclick="showAddModal()">
          新增知识库
        </button>
      </div>

      <div class="table-responsive">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>ID</th>
              <th>名称</th>
              <th>描述</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody id="knowledgeList">
            <!-- 数据将通过JavaScript动态加载 -->
          </tbody>
        </table>
        <!-- 添加分页控件 -->
        <nav aria-label="Page navigation">
          <ul class="pagination justify-content-end" id="pagination"></ul>
        </nav>
      </div>
    </div>

    <!-- 添加/编辑知识库模态框 -->
    <div class="modal fade" id="knowledgeModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="modalTitle">新增知识库</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
            ></button>
          </div>
          <div class="modal-body">
            <form id="knowledgeForm">
              <input type="hidden" id="knowledgeId" />
              <input type="hidden" id="version" />
              <div class="mb-3">
                <label for="name" class="form-label">名称</label>
                <input type="text" class="form-control" id="name" required />
              </div>
              <div class="mb-3">
                <label for="description" class="form-label">描述</label>
                <textarea
                  class="form-control"
                  id="description"
                  rows="3"
                ></textarea>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-primary"
              onclick="saveKnowledge()"
            >
              保存
            </button>
          </div>
        </div>
      </div>
    </div>

    <script>
      let currentPage = 1;
      let pageSize = 10;
      let totalPages = 0;

      // 页面加载完成后获取知识库列表
      $(document).ready(function () {
        loadKnowledgeList(1);
      });

      // 加载知识库列表
      function loadKnowledgeList(pageNo) {
        currentPage = pageNo;
        $.ajax({
          url: '/knowledge/tables',
          method: 'POST',
          contentType: 'application/json',
          data: JSON.stringify({
            pageNo: pageNo,
            pageSize: pageSize,
            searchParams: [],
            sortOptions: []
          }),
          success: function (response) {
            if (response.code === 200) {
              const data = response.data;
              let html = '';
              data.records.forEach(function (item) {
                html += `
                  <tr>
                    <td>${item.id}</td>
                    <td>${item.name}</td>
                    <td>${item.description}</td>
                    <td>${item.createTime}</td>
                    <td class="action-buttons">
                      <button class="btn btn-sm btn-info" onclick="editKnowledge(${item.id})">编辑</button>
                      <button class="btn btn-sm btn-danger" onclick="deleteKnowledge(${item.id})">删除</button>
                    </td>
                  </tr>
                `;
              });
              $('#knowledgeList').html(html);

              // 更新分页信息
              totalPages = data.pages;
              updatePagination();
            } else {
              alert('加载失败：' + response.message);
            }
          },
          error: function (xhr) {
            alert('加载知识库列表失败：' + xhr.responseText);
          }
        });
      }

      // 更新分页控件
      function updatePagination() {
        let paginationHtml = '';

        // 如果没有数据，不显示分页控件
        if (totalPages === 0) {
          $('#pagination').html('');
          return;
        }

        // 上一页按钮
        paginationHtml += `
          <li class="page-item ${
            currentPage === 1 || totalPages === 0 ? 'disabled' : ''
          }">
            <a class="page-link" href="javascript:void(0)" onclick="loadKnowledgeList(${
              currentPage - 1
            })" aria-label="Previous">
              <span aria-hidden="true">&laquo;</span>
            </a>
          </li>
        `;

        // 页码按钮
        // 当页数过多时，显示省略号
        const maxVisiblePages = 5;
        let startPage = Math.max(
          1,
          currentPage - Math.floor(maxVisiblePages / 2)
        );
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

        // 调整起始页，确保显示足够的页码
        if (endPage - startPage + 1 < maxVisiblePages) {
          startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        // 添加第一页
        if (startPage > 1) {
          paginationHtml += `
            <li class="page-item">
              <a class="page-link" href="javascript:void(0)" onclick="loadKnowledgeList(1)">1</a>
            </li>
          `;
          if (startPage > 2) {
            paginationHtml += `
              <li class="page-item disabled">
                <span class="page-link">...</span>
              </li>
            `;
          }
        }

        // 添加中间的页码
        for (let i = startPage; i <= endPage; i++) {
          paginationHtml += `
            <li class="page-item ${currentPage === i ? 'active' : ''}">
              <a class="page-link" href="javascript:void(0)" onclick="loadKnowledgeList(${i})">${i}</a>
            </li>
          `;
        }

        // 添加最后一页
        if (endPage < totalPages) {
          if (endPage < totalPages - 1) {
            paginationHtml += `
              <li class="page-item disabled">
                <span class="page-link">...</span>
              </li>
            `;
          }
          paginationHtml += `
            <li class="page-item">
              <a class="page-link" href="javascript:void(0)" onclick="loadKnowledgeList(${totalPages})">${totalPages}</a>
            </li>
          `;
        }

        // 下一页按钮
        paginationHtml += `
          <li class="page-item ${
            currentPage === totalPages || totalPages === 0 ? 'disabled' : ''
          }">
            <a class="page-link" href="javascript:void(0)" onclick="loadKnowledgeList(${
              currentPage + 1
            })" aria-label="Next">
              <span aria-hidden="true">&raquo;</span>
            </a>
          </li>
        `;

        $('#pagination').html(paginationHtml);
      }

      // 显示添加模态框
      function showAddModal() {
        $('#modalTitle').text('新增知识库');
        $('#knowledgeId').val('');
        $('#name').val('');
        $('#description').val('');
        $('#knowledgeModal').modal('show');
      }

      // 保存知识库
      function saveKnowledge() {
        const id = $('#knowledgeId').val();
        const data = {
          name: $('#name').val(),
          description: $('#description').val()
        };

        if (id) {
          data.id = id;
          // 从编辑表单中获取版本号
          const version = $('#version').val();
          if (version) {
            data.version = parseInt(version);
          }
        }

        $.ajax({
          url: '/knowledge/save',
          method: 'POST',
          contentType: 'application/json',
          data: JSON.stringify(data),
          success: function () {
            $('#knowledgeModal').modal('hide');
            loadKnowledgeList(currentPage); // 保持在当前页
            alert('保存成功');
          },
          error: function (xhr) {
            alert('保存失败：' + xhr.responseText);
          }
        });
      }

      // 显示编辑模态框
      function editKnowledge(id) {
        $('#modalTitle').text('编辑知识库');
        // 获取知识库详情
        $.ajax({
          url: '/knowledge/show',
          method: 'POST',
          contentType: 'application/json',
          data: JSON.stringify({
            id: id
          }),
          success: function (response) {
            if (response.code === 200) {
              const data = response.data;
              $('#knowledgeId').val(data.id);
              $('#name').val(data.name);
              $('#description').val(data.description);
              // 添加版本号到隐藏字段
              $('#version').val(data.version);
              $('#knowledgeModal').modal('show');
            } else {
              alert('获取知识库详情失败：' + response.message);
            }
          },
          error: function (xhr) {
            alert('获取知识库详情失败：' + xhr.responseText);
          }
        });
      }

      // 修改删除知识库成功后的处理
      function deleteKnowledge(id) {
        if (confirm('确定要删除这个知识库吗？')) {
          $.ajax({
            url: '/knowledge/delete',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
              ids: [id]
            }),
            success: function () {
              loadKnowledgeList(currentPage); // 保持在当前页
              alert('删除成功');
            },
            error: function (xhr) {
              alert('删除失败：' + xhr.responseText);
            }
          });
        }
      }
    </script>
  </body>
</html>
